<template>
  <div class="margin-top">
    <!-- 搜索和添加管理员功能 -->
    <el-input v-model="searchValue" placeholder="请输入管理员名或自习室" style="width: 200px; margin-bottom: 10px;"></el-input>
    <el-button type="primary" size="small" @click="searchAdmin">搜索管理员</el-button>
    <el-button type="primary" size="small" @click="showAddAdminDialog">添加管理员</el-button>

    <!-- 管理员信息表格 -->
    <el-table :data="filteredAdmins" style="width: 100%">
      <el-table-column prop="rid" label="管理员ID"></el-table-column>
      <el-table-column prop="rname" label="管理员名称"></el-table-column>
      <el-table-column prop="rpass" label="管理员密码"></el-table-column>
      <el-table-column prop="room" label="负责的自习室"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="showModifyAdminDialog(scope.row)">修改管理员</el-button>
          <el-button type="primary" size="small" @click="deleteAdminDialog(scope.row.rid)">删除管理员</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加管理员对话框 -->
    <el-dialog :visible.sync="addAdminDialogVisible" title="添加管理员">
      <el-form :model="addAdminForm" ref="addAdminForm" :rules="addAdminRules" label-width="100px">
        <el-form-item label="管理员名称" prop="rname">
          <el-input v-model="addAdminForm.rname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员密码" prop="rpass">
          <el-input type="password" v-model="addAdminForm.rpass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属自习室" prop="room">
          <el-input v-model="addAdminForm.room" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAdminDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="validateAndAddAdmin">确认</el-button>
      </span>
    </el-dialog>

    <!-- 修改管理员对话框 -->
    <el-dialog :visible.sync="modifyAdminDialogVisible" title="修改管理员信息">
      <el-form :model="modifyAdminForm" ref="modifyAdminForm" :rules="modifyAdminRules" label-width="100px">
        <el-form-item label="管理员ID">
          <el-input v-model="modifyAdminForm.rid" disabled></el-input>
        </el-form-item>
        <el-form-item label="管理员名称">
          <el-input v-model="modifyAdminForm.rname" disabled></el-input>
        </el-form-item>
        <el-form-item label="管理员密码" prop="rpass">
          <el-input v-model="modifyAdminForm.rpass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属自习室" prop="room">
          <el-input v-model="modifyAdminForm.room" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyAdminDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="validateAndModifyAdmin">确认修改</el-button>
      </span>
    </el-dialog>

    <!-- 删除管理员对话框 -->
    <el-dialog :visible.sync="deleteAdminDialogVisible" title="确认删除管理员">
      <p>确定要删除该管理员吗？</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteAdminDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDeleteAdmin">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      searchValue: '', // 搜索框输入的值
      admins: [], // 管理员列表
      addAdminDialogVisible: false, // 添加管理员对话框显示状态
      modifyAdminDialogVisible: false, // 修改管理员对话框显示状态
      deleteAdminDialogVisible: false, // 删除管理员对话框显示状态
      addAdminForm: {
        rname: '',
        rpass: '',
        room: ''
      }, // 添加管理员表单数据
      modifyAdminForm: {
        rid: '',
        rname: '',
        rpass: '',
        room: ''
      }, // 修改管理员表单数据
      addAdminRules: {
        rname: [{ required: true, message: '请输入管理员名称', trigger: 'blur' }],
        rpass: [{ required: true, message: '请输入管理员密码', trigger: 'blur' }],
        room: [{ required: true, message: '请输入所属自习室', trigger: 'blur' }],
      }, // 添加管理员表单验证规则
      modifyAdminRules: {
        room: [
          { required: true, message: '请输入所属自习室', trigger: 'blur' },
          {
            validator: async (rule, value, callback) => {
              const roomName = await this.getAllRoomName();
              if (roomName.includes(value)) {
                callback();
              } else {
                callback(new Error('该自习室不存在'));
              }
            },
            trigger: 'blur'
          }
        ],
      }, // 修改管理员表单验证规则
      deleteAdminId: null, // 待删除的管理员ID
    };
  },
  created() {
    this.fetchAdmins(); // 组件创建时获取管理员列表
  },
  computed: {
    filteredAdmins() {
      return this.admins.filter(admin => {
        return admin.rname.includes(this.searchValue) || admin.room.includes(this.searchValue);
      });
    } // 根据搜索框输入的值过滤管理员列表
  },
  methods: {
    async getAllRoomName() {
      // 获取所有自习室名称
      try {
        const response = await axios.get('http://localhost:7070/api/superadmin/allroomname');
        return response.data.map(room => room.roomName);
      } catch (error) {
        console.error('获取自习室名称列表失败:', error);
        return [];
      }
    },
    async fetchAdmins() {
      // 获取所有管理员信息
      try {
        const response = await axios.get('http://localhost:7070/api/superadmin/allstudyroomadmin');
        this.admins = response.data;
      } catch (error) {
        console.error('获取管理员列表失败:', error);
      }
    },
    searchAdmin() {
      // 搜索管理员
      console.log('搜索管理员：', this.searchValue);
    },
    showAddAdminDialog() {
      // 显示添加管理员对话框
      this.addAdminDialogVisible = true;
    },
    validateAndAddAdmin() {
      // 验证并添加管理员
      this.$refs.addAdminForm.validate(async valid => {
        if (valid) {
          const roomName = await this.getAllRoomName();
          if (roomName.includes(this.addAdminForm.room)) {
            await this.addAdmin();
          } else {
            this.$message.error('该自习室不存在');
          }
        } else {
          return false;
        }
      });
    },
    async addAdmin() {
      // 添加管理员
      console.log('添加管理员：', this.addAdminForm);
      try {
        const response = await axios.post('http://localhost:7070/api/superadmin/addstudyroomadmin', this.addAdminForm);
        console.log('添加管理员成功：', response.data);
        this.$refs.addAdminForm.resetFields();
        this.addAdminDialogVisible = false;
        await this.fetchAdmins();
        this.$message.success('添加管理员成功！');
      } catch (error) {
        console.error('添加管理员失败:', error);
        this.$message.error('添加管理员失败！');
      }
    },
    deleteAdminDialog(rid) {
      // 显示删除管理员对话框
      this.deleteAdminId = rid;
      this.deleteAdminDialogVisible = true;
    },
    async confirmDeleteAdmin() {
      // 确认删除管理员
      console.log('确认删除管理员，管理员id：', this.deleteAdminId);
      try {
        const response = await axios.delete(`http://localhost:7070/api/superadmin/deletestudyroomadmin/${this.deleteAdminId}`);
        console.log('删除管理员成功：', response.data);
        this.deleteAdminDialogVisible = false;
        await this.fetchAdmins();
        this.$message.success('删除管理员成功！');
      } catch (error) {
        console.error('删除管理员失败:', error);
        this.$message.error('删除管理员失败！');
      }
    },
    showModifyAdminDialog(admin) {
      // 显示修改管理员对话框
      this.modifyAdminForm = { ...admin };
      this.modifyAdminDialogVisible = true;
    },
    validateAndModifyAdmin() {
      // 验证并修改管理员信息
      this.$refs.modifyAdminForm.validate(async valid => {
        if (valid) {
          const roomName = await this.getAllRoomName();
          if (roomName.includes(this.modifyAdminForm.room)) {
            await this.modifyAdmin();
          } else {
            this.$message.error('该自习室不存在');
          }
        } else {
          return false;
        }
      });
    },
    async modifyAdmin() {
      // 修改管理员信息
      console.log('修改管理员信息：', this.modifyAdminForm);
      try {
        const response = await axios.put(`http://localhost:7070/api/superadmin/modifystudyroomadmin/${this.modifyAdminForm.rid}`, this.modifyAdminForm);
        console.log('修改管理员成功：', response.data);
        this.$refs.modifyAdminForm.resetFields();
        this.modifyAdminDialogVisible = false;
        await this.fetchAdmins();
        this.$message.success('修改管理员成功！');
      } catch (error) {
        console.error('修改管理员失败:', error);
        this.$message.error('修改管理员失败！');
      }
    },
  }
};
</script>

<style scoped>
.margin-top {
  margin-top: 1px;
}
</style>
